use std::sync::{Arc, RwLock};
use std::thread;

fn main() {
    //创建一个共享的变量整数，使用RwLock包装
    let counter = Arc::new(RwLock::new(0));
    //创建一个多线程读取计数器
    // let mut read_handles = vec![];

    //创建一个线程持有读锁
    let read_handle = {
        let counter = counter.clone();
        thread::spawn(move || {
            //获取读锁
            let num = counter.read().unwrap();
            println!("Reader #1{:?}: {}", thread::current().id(), *num);

            //尝试写锁，导致死锁
            let mut num = counter.write().unwrap();
            *num += 1;
            println!(
                "Reader {:?}: Incremented counter to {}",
                thread::current().id(),
                *num
            );
        })
    };

    //创建一个线程来写入计算器的值
    let write_handle = {
        let counter = counter.clone();
        thread::spawn(move || {
            //尝试获取写锁
            let mut num = counter.write().unwrap();
            *num += 1;
            println!(
                "Writer {:?}: Incremented counter to {}",
                thread::current().id(),
                *num
            );

            //尝试读锁，导致死锁
            let num = counter.read().unwrap();
            println!("Writer {:?}: {}", thread::current().id(), *num);
        })
    };

    //等待所有线程执行完成
    //等待写入线程完成
    read_handle.join().unwrap();
    write_handle.join().unwrap();
}
